package com.idea.cery.springboot1.service.impl;

import com.idea.cery.springboot1.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.Future;

/**
 * @Author:cery
 * @Version 1.0
 * @Date:2020/4/9
 */
@Service
public class AsyncServiceImpl implements AsyncService {

    private static Random random = new Random();

    @Async //使用异步需要 在application 中配置 @EnableAsync
    @Override
    public Future<String> doTask1() throws Exception {

        Future<String> str = new AsyncResult<>("任务一");

        System.out.println("任务一开始");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));//随机一个等待时间
        long end = System.currentTimeMillis();
        System.out.println("任务一结束，耗时" + (end - start) + "毫秒");

        return str;
    }

    @Async
    @Override
    public Future<String> doTask2() throws Exception {
        Future<String> str = new AsyncResult<>("任务二");

        System.out.println("任务二开始");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));//随机一个等待时间
        long end = System.currentTimeMillis();
        System.out.println("任务二结束，耗时" + (end - start) + "毫秒");

        return str;
    }

    @Async
    @Override
    public Future<String> doTask3() throws Exception {
        Future<String> str = new AsyncResult<>("任务三");

        System.out.println("任务三开始");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));//随机一个等待时间
        long end = System.currentTimeMillis();
        System.out.println("任务三结束，耗时" + (end - start) + "毫秒");

        return str;
    }
}
